package com.ztom.top100;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 对称二叉树
 * <p>
 * https://leetcode-cn.com/problems/symmetric-tree/
 *
 * @author ZhangTao
 */
public class Code40IsSymmetric {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 递归
     *
     * @param root
     * @return
     */
    public boolean isSymmetric1(TreeNode root) {
        if (root == null) {
            return true;
        }

        return isSymmetric(root.left, root.right);
    }

    public boolean isSymmetric(TreeNode left, TreeNode right) {
        // 都为空, 对称
        if (left == null && right == null) {
            return true;
        }
        // 一个空, 一个不为空, 不对称
        if (left == null || right == null) {
            return false;
        }
        if (left.val != right.val) {
            return false;
        }

        return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
    }


    /**
     * 迭代
     *
     * @param root
     * @return
     */
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }

        Deque<TreeNode> queue = new LinkedList<>();
        queue.addFirst(root.left);
        queue.addFirst(root.right);

        while (!queue.isEmpty()) {
            TreeNode left = queue.pollLast();
            TreeNode right = queue.pollLast();
            if (left == null && right == null) {
                continue;
            }
            if (left == null || right == null) {
                return false;
            }
            if (left.val != right.val) {
                return false;
            }
            queue.addFirst(left.left);
            queue.addFirst(right.right);
            queue.addFirst(left.right);
            queue.addFirst(right.left);
        }

        return true;
    }
}
